package com.nowcoder.community.contorller.advice;

import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//统一异常处理
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(Exception.class);

    @ExceptionHandler({Exception.class})
    public void handleExcetion(Exception e, HttpServletRequest request, HttpServletResponse response){
        logger.error("服务器发送异常："+e.getMessage());

        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }

        //判断是否为异步ajax请求
        String xRequestedWith = request.getHeader("x-requested-with");
        if("XMLHttpRequest".equals(xRequestedWith)){
            response.setContentType("application/plain;charset=utf-8");
            try {
                PrintWriter writer = response.getWriter();
                writer.write(CommunityUtil.getJSONString(1,"服务器异常"));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }else{
            try {
                response.sendRedirect(request.getContextPath()+"/error");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
}
